package com.mayfool.gitmanager.ui.dialog;

import com.mayfool.gitmanager.core.entity.BranchCreateResult;
import com.mayfool.gitmanager.core.entity.TaskInfo;
import com.mayfool.gitmanager.core.enums.BranchCreateStatus;
import com.mayfool.gitmanager.core.helper.GitOperations;
import com.mayfool.gitmanager.core.helper.LogHelper;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.List;

/**
 * 分支创建对话框
 * 
 * @author zhou.xu
 * @date 2024-03-18 16:30:00
 */
public class BranchCreateDialog extends JDialog {
    private final TaskInfo task;
    private final GitOperations gitOps;
    
    private JTextField branchNameField;
    private JTextField startPointField;
    private JCheckBox pushToRemoteBox;
    private JButton createButton;
    private JButton cancelButton;
    
    public BranchCreateDialog(Frame owner, TaskInfo task, GitOperations gitOps) {
        super(owner, "创建新分支", true);
        this.task = task;
        this.gitOps = gitOps;
        
        initComponents();
        setupLayout();
    }
    
    private void initComponents() {
        // 分支名称输入框
        branchNameField = new JTextField(20);
        
        // 起始点输入框（可选）
        startPointField = new JTextField(20);
        
        // 推送到远程选项
        pushToRemoteBox = new JCheckBox("推送到远程仓库", true);
        
        // 按钮
        createButton = new JButton("创建");
        createButton.addActionListener(e -> handleCreate());
        
        cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dispose());
    }
    
    private void setupLayout() {
        setLayout(new BorderLayout());
        
        // 输入面板
        JPanel inputPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        
        // 分支名称
        gbc.gridx = 0;
        gbc.gridy = 0;
        inputPanel.add(new JLabel("分支名称:"), gbc);
        
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        inputPanel.add(branchNameField, gbc);
        
        // 起始点
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0;
        inputPanel.add(new JLabel("起始点:"), gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 1.0;
        inputPanel.add(startPointField, gbc);
        
        // 推送到远程选项
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        inputPanel.add(pushToRemoteBox, gbc);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(cancelButton);
        buttonPanel.add(createButton);
        
        // 添加到主面板
        add(inputPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
        
        // 设置对话框大小和位置
        pack();
        setLocationRelativeTo(getOwner());
    }
    
    private void handleCreate() {
        String branchName = branchNameField.getText().trim();
        if (branchName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入分支名称", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        String startPoint = startPointField.getText().trim();
        if (startPoint.isEmpty()) {
            startPoint = null;
        }
        
        boolean pushToRemote = pushToRemoteBox.isSelected();
        
        // 禁用创建按钮
        createButton.setEnabled(false);
        
        // 在新线程中执行创建操作
        String finalStartPoint = startPoint;
        new Thread(() -> {
            try {
                LogHelper.getInstance().info("开始创建分支...");
                
                List<BranchCreateResult> results = gitOps.createBranchForAll(
                    branchName,
                    finalStartPoint,
                    pushToRemote
                );
                
                // 处理结果
                boolean hasError = false;
                for (BranchCreateResult result : results) {
                    String projectName = new File(result.getProjectPath()).getName();
                    if (result.getStatus() == BranchCreateStatus.SUCCESS) {
                        LogHelper.getInstance().info(String.format("[%s] 创建成功", projectName));
                    } else {
                        hasError = true;
                        LogHelper.getInstance().error(String.format("[%s] %s: %s",
                            projectName,
                            result.getStatus().getMessage(),
                            result.getErrorMessage() != null ? result.getErrorMessage() : ""
                        ));
                    }
                }
                
                if (!hasError) {
                    LogHelper.getInstance().info("所有项目创建分支完成。");
                    // 延迟关闭对话框
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this, "分支创建成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                        dispose();
                    });
                } else {
                    LogHelper.getInstance().warn("部分项目创建分支失败，请查看日志了解详情。");
                }
                
            } finally {
                // 恢复创建按钮
                SwingUtilities.invokeLater(() -> createButton.setEnabled(true));
            }
        }).start();
    }
} 